package com.rabbitClient.direct;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

public class Customer {
	
	public static final String EXCHANGE_NAME = "rabbitClient.routing";
	public static final String QUEUE_NAME = "rabbitClient.routing.queue";
	public static final String HOST = "192.168.1.235";
	public static final String USER = "guest";
	public static final String PASSWORD = "guest";
	public static final int PORT = 5672;
	public static final String VIRTUAL_HOST = "test";
	
	public static void main(String[] args) throws IOException, TimeoutException {
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost(HOST);
		factory.setPort(PORT);
		factory.setVirtualHost(VIRTUAL_HOST);
		factory.setUsername(USER);
		factory.setPassword(PASSWORD);
		
		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel();
		channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "info");
		System.out.println("Customer wait received messages:");
		Consumer consumer = new DefaultConsumer(channel) {
			//会阻塞，持续等到新的消息进入队列，一旦有新的消息就进行接收并处理消息
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope,
                    AMQP.BasicProperties properties, byte[] body) throws IOException {
				String message = new String (body, "UTF-8");
				System.out.println(message);
				
				//消费者未能消费此消息
				//第三个参数，将这个消息重新放入到队列中，那么此消费者会持续受到这条消息
//				channel.basicNack(envelope.getDeliveryTag(), false, true);
				
			}
		};
		//自动回复队列应答
		channel.basicConsume(QUEUE_NAME, true, consumer);
		
		
	}
}
